extends CharacterBody2D
signal player_died
## 重力
@export var gravity:int = 1600
## 弹力
@export var jump_power:int = 600
## 摄像机
@export var carmera:Camera2D
## 精灵
@onready var sprite:AnimatedSprite2D = $AnimatedSprite2D
## 跳跃音效
@onready var jump_sound:AudioStreamPlayer = $JumpSound
## 死亡音效
@onready var death_sound:AudioStreamPlayer = $DeathSound
## 发射火球音效
@onready var shoot_sound = $ShootSound
## 碰撞盒
@onready var collision_shape:CollisionShape2D = $CollisionShape2D
@onready var projectile_position = $ProjectilePosition
@onready var game = $"/root/World"

var active:bool=true
var jumps_remaing:int=2
var was_jumping:bool=false
var ammo:int=3
var jump_patch:float=1.0

## 火球
var projectile = preload('res://scenes/projectile.tscn')

func _ready():
	sprite.animation_finished.connect(_on_animation_finished)
	
# 物理更新
func _physics_process(delta):
	# 坠落速度
	velocity.y += gravity*delta
	
	if active:
		# 更新相机位置
		carmera.position = position
		# 角色落地后重置
		if was_jumping and is_on_floor():
			was_jumping=false
			jumps_remaing=2
			sprite.play('run')
			jump_patch=1.0
			
		# 跳跃逻辑
		if Input.is_action_just_pressed('jump') and  jumps_remaing > 0:
			jumps_remaing -= 1
			was_jumping = true
			velocity.y = -jump_power
			# 执行动画
			if jumps_remaing == 1:
				sprite.play('jump')
			else :
				sprite.play('double jump')
			# 设置音频 二次跳跃音频不一样
			jump_sound.set_pitch_scale(jump_patch)
			jump_sound.play()
			jump_patch+=0.2
	# 移动物体	
	move_and_slide()

# 输入事件
func _input(event):
	if event.is_action_pressed('fire') and ammo > 0 and active==true :
		var projectil_instance=projectile.instantiate()
		projectil_instance.position=projectile_position.global_position
		game.add_child(projectil_instance)
		shoot_sound.play()
		sprite.play('shoot')
		ammo-=1
	
# 死亡事件
func die():
	death_sound.play()
	sprite.play('death')
	active=false
	collision_shape.set_deferred('disable',true)
	emit_signal('player_died')
	pass

func _on_animation_finished():
	if sprite.animation=="shoot":
		sprite.play("run")

func add_ammo(value):
	ammo += value
	ammo = clamp(ammo,0,3)
